#pragma once

#include <iostream>
#include <string>
#include <sys/select.h>
#include <sys/time.h>
#include "Socket.hpp"

static const uint16_t defaultport = 8888;
static const int fd_num_max = (sizeof(fd_set) * 8);
int defaultfd = -1;

class SelectServer
{
public:
    SelectServer(uint16_t port = defaultport) : _port(port)
    {
        for(int i = 0; i < fd_num_max; i++)
            fd_array[i] = defaultfd;
    }
    bool Init()
    {
        _listensock.Socket();
        _listensock.Bind(_port);
        _listensock.Listen();

        return true;
    }

    void Accepter()
    {
        std::string clientip;
        uint16_t clientport = 0;
        int sock = _listensock.Accept(&clientip, &clientport);
        if(sock < 0) return;
        lg(Info, "accept success, %s: %d, sock fd: %d", clientip, clientport, sock);

        int pos = 1;
        for(; pos < fd_num_max; pos++)
        {
            if(fd_array[pos] != defaultfd) continue;
            else break;
        }
        if(pos == fd_num_max)
        {
            lg(Warning, "server is full, close %d now!", sock);
            close(sock);
        }
        else
        {
            fd_array[pos] = sock;
            PrintFd();
            // TODO
        }
    }
    void Recver(int fd, int pos)
    {
        // demo
        char buffer[1024];
        ssize_t n = read(fd, buffer, sizeof(buffer) - 1); // bug? tcp发来的报文肯能不完整, 需要做分析
        if(n > 0)
        {
            buffer[n - 1] = 0; // 这里再减一是为了覆盖掉 '\n'
            std::cout << "get a message: " << buffer << std::endl << std::endl;
        }
        else if(n == 0) // 读到 0 意味着客户端退出了
        {
            lg(Info, "client quit, me too, close fd is: %d", fd);
            close(fd);
            fd_array[pos] = defaultfd; // 这里本质是从 select 中移除
        }
        else
        {
            lg(Warning, "recv error, fd is: %d", fd);
            close(fd);
            fd_array[pos] = defaultfd;
        }
    }
    void Dispatcher(fd_set& rfds)
    {
        for(int i = 0; i < fd_num_max; i++)
        {
            int fd = fd_array[i];
            if(fd == defaultfd) continue;

            if(FD_ISSET(fd, &rfds))
            {
                if(fd == _listensock.Fd()) // listen套接字
                {
                    Accepter(); // 链接管理器
                }
                else // non listen, 读事件就绪
                {
                    Recver(fd, i);
                }
            }
        }
    }
    void Start()
    {
        int listensock = _listensock.Fd();
        fd_array[0] = listensock;

        for(;;)
        {
            fd_set rfds;
            FD_ZERO(&rfds); // 对每一位置零

            int maxfd = fd_array[0];
            for(int i = 0; i < fd_num_max; i++)
            {
                if(fd_array[i] == defaultfd) continue;
                FD_SET(fd_array[i], &rfds);
                if(maxfd < fd_array[i])
                {
                    maxfd = fd_array[i];
                    lg(Info, "max fd update, max fd is: %d", maxfd);
                }
            }

            // 不能直接 accept! 检查并获取 listensock 上面的事件，新连接到来，等价于读事件就绪
            // struct timeval timeout = {1, 0}; // 输入输出，可能要进行周期的重新设置
            struct timeval timeout = { 0, 0 };
            // 如果事件就绪，上层不处理，select会一直通知！！！
            // select 告诉你就绪了，接下来一次读取 fd，不会阻塞
            // rfds 输入输出型参数。 1111 1111 -> 0000 0000
            int n = select(maxfd + 1, &rfds, nullptr, nullptr, /*timeout*/nullptr);
            switch(n)
            {
            case 0:
                std::cout << "time out, timeout: " << n << std::endl;
                break;
            case -1:
                std::cout << "select error" << std::endl;
                break;
            default:
                // 有事件就绪了
                std::cout << "get a new link!!!" << std::endl;
                Dispatcher(rfds); // 事件派发器，就绪的事件可能不止一个！！！
                break;
            }
        }
    }
    void PrintFd()
    {
        std::cout << "online fd list: ";
        for(int i = 0; i < fd_num_max; i++)
        {
            if(fd_array[i] == defaultfd) continue;
            else std::cout << fd_array[i] << " ";
        }
        std::cout << std::endl;
    }
    ~SelectServer()
    {}
private:
    Sock _listensock;
    uint16_t _port;
    int fd_array[fd_num_max]; // 辅助数组
};
